﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace AdbService
{
    /// <summary>
    /// ADB命令执行服务实现
    /// </summary>
    public class AdbCommandService : IAdbCommandService
    {
        public event AdbCommandEventHandler CommandExecuted;
        public event AdbCommandEventHandler CommandError;
        ProcessStartInfo startInfo = ProcessStartInfoManager.GetDefaultCmdStartInfo();
        private string _workingDirectory = $"{AppDomain.CurrentDomain.BaseDirectory}adb";

        /// <summary>
        /// 执行ADB命令（同步版本）
        /// </summary>
        public string ExecuteAdbCommand(string command, string operationName = "")
        {
            try
            {
                if (!string.IsNullOrEmpty(operationName))
                {
                    OnCommandExecuted(command, $"开始执行: {operationName}", operationName);
                }

                string result = ExecuteCommandInternal(command, _workingDirectory);

                if (!string.IsNullOrEmpty(operationName))
                {
                    OnCommandExecuted(command, $"{result}{Environment.NewLine}{operationName} 执行完成", operationName);
                }
                else
                {
                    OnCommandExecuted(command, result, operationName);
                }

                return result;
            }
            catch (Exception ex)
            {
                string errorMessage = $"执行命令时出错: {ex.Message}";
                OnCommandError(command, errorMessage, operationName);
                return errorMessage;
            }
        }

        /// <summary>
        /// 执行ADB命令（异步版本）
        /// </summary>
        public async Task<string> ExecuteAdbCommandAsync(string command, string operationName = "")
        {
            return await Task.Run(() => ExecuteAdbCommand(command, operationName));
        }

        /// <summary>
        /// 设置ADB工作目录
        /// </summary>
        public void SetWorkingDirectory(string directory)
        {
            if (!string.IsNullOrEmpty(directory))
            {
                _workingDirectory = directory;
            }
        }

        /// <summary>
        /// 获取ADB工作目录
        /// </summary>
        public string GetWorkingDirectory()
        {
            return _workingDirectory;
        }

        /// <summary>
        /// 触发命令执行完成事件
        /// </summary>
        protected virtual void OnCommandExecuted(string command, string result, string operationName)
        {
            CommandExecuted?.Invoke(this, new AdbCommandEventArgs(command, result, operationName));
        }

        /// <summary>
        /// 触发命令执行错误事件
        /// </summary>
        protected virtual void OnCommandError(string command, string errorMessage, string operationName)
        {
            CommandError?.Invoke(this, new AdbCommandEventArgs(command, errorMessage, operationName, true));
        }

        /// <summary>
        /// 内部命令执行方法
        /// </summary>
        private string ExecuteCommandInternal(string command, string path)
        {
            StringBuilder result = new StringBuilder();

            

            using (Process process = new Process())
            {
                process.StartInfo = startInfo;

                // 输出数据接收
                process.OutputDataReceived += (s, e) =>
                {
                    if (!string.IsNullOrEmpty(e.Data))
                    {
                        result.AppendLine(e.Data);
                    }
                };

                // 错误数据接收
                process.ErrorDataReceived += (s, e) =>
                {
                    if (!string.IsNullOrEmpty(e.Data))
                    {
                        result.AppendLine($"Error: {e.Data}");
                    }
                };

                process.Start();
                process.BeginOutputReadLine();
                process.BeginErrorReadLine();

                // 写入命令
                if (!string.IsNullOrEmpty(command))
                {
                    process.StandardInput.WriteLine(command);
                    Thread.Sleep(300); // 给命令执行一些时间
                }

                process.StandardInput.WriteLine("exit");

                // 等待进程结束
                if (!process.WaitForExit(5000))
                {
                    process.Kill();
                    result.AppendLine("Command execution timeout.");
                }

                Thread.Sleep(100); // 确保所有输出被捕获
            }

            return result.ToString();
        }
    }
}
